<script lang="ts" setup>
import {onMounted, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {open as openDialog} from "@tauri-apps/plugin-dialog";
import {executeCommand} from "../utils/ipc";
import {useSettingStore} from "../stores/setting";

const props = defineProps<{
  visible: boolean
}>();

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'settings-saved'): void
}>();

const settingStore = useSettingStore();
const cvsPath = ref(settingStore.cvsPath);
const cvsVersion = ref<string>();

let versionTimer: ReturnType<typeof setTimeout> | null = null;

onMounted(() => {
  if (settingStore.cvsPath) {
    loaderCvsVersion(settingStore.cvsPath);
  }
});

watch(cvsPath, (newPath) => {
  cvsVersion.value = '';
  if (versionTimer) {
    clearTimeout(versionTimer);
  }
  if (newPath) {
    versionTimer = setTimeout(() => {
      loaderCvsVersion(newPath);
    }, 1000);
  } else {
    cvsVersion.value = '';
  }
});

async function loaderCvsVersion(path: string) {
  try {
    const result = await executeCommand(path, ['--version']);
    const version = result.match(/\d+(\.\d+)+/);
    cvsVersion.value = version ? version[0] : '';
  } catch (error) {
    console.error('获取CVS版本失败:', error);
    cvsVersion.value = '';
  }
}

function resetDialogData() {
  cvsPath.value = settingStore.cvsPath;
  if (settingStore.cvsPath) {
    loaderCvsVersion(settingStore.cvsPath);
  } else {
    cvsVersion.value = undefined;
  }
}

watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    cvsPath.value = settingStore.cvsPath;
    if (settingStore.cvsPath) {
      loaderCvsVersion(settingStore.cvsPath);
    }
  }
}, { immediate: true });

onMounted(() => {
  resetDialogData();
});

const selectCvsPath = async () => {
  try {
    const selected = await openDialog({
      multiple: false,
      filters: [{
        name: 'Executable Files',
        extensions: ['exe']
      }]
    });
    cvsPath.value = selected || '';
  } catch (error) {
    console.error('选择CVS路径失败:', error);
    ElMessage.error('选择CVS路径失败');
  }
};

const saveSettings = () => {
  if (!cvsPath.value) {
    ElMessage.error('CVS路径不能为空');
    return;
  }
  settingStore.cvsPath = cvsPath.value;
  ElMessage.success('设置已保存');
  emit('update:visible', false);
  emit('settings-saved');
};

const closeDialog = () => {
  if (versionTimer) {
    clearTimeout(versionTimer);
    versionTimer = null;
  }
  emit('update:visible', false);
  resetDialogData();
};

</script>

<template>
  <el-dialog
      v-model="props.visible"
      destroy-on-close
      title="设置"
      width="60%"
      @closed="closeDialog">
    <div class="settings-form">
      <el-form label-position="left">
        <el-form-item label="CVS路径">
          <el-input v-model="cvsPath" placeholder="CVS可执行文件的完整路径">
            <template #suffix>
              <span class="mr-2 text-[0.9rem] select-none">{{ cvsVersion }}</span>
              <div class="i-fluent:folder-32-regular !h-5 !w-5 cursor-pointer" @click="selectCvsPath"/>
            </template>
          </el-input>
          <div class="text-gray-500 text-sm mt-1">
            例如: C:\Program Files\CVS\cvs.exe
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveSettings">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.settings-form {
  padding: 0 10px;
}
</style>